package lua.compiler.tokens;

import lua.compiler.CompilerException;
import lua.compiler.Function;

import org.antlr.runtime.tree.Tree;

public class StmtToken extends GenericToken {

	@Override
	public void parseImpl(Tree tree, Function function) throws CompilerException {
		int type = tree.getType();
		String token = Tokens.getToken(type);
		GenericToken genericToken;

		if (token.equals("DEF")) {
			// function musi byc rowne main (nie definiujemy funkcji w obrebie innych funkcji)
			genericToken = new DefToken();
			genericToken.parse(tree, function);
		}
		else if (token.equals("ASSIGN")) {
			genericToken = new AssignToken();
			genericToken.parse(tree, function);
		}
		else if (token.equals("CALL")) {
			genericToken =  new CallToken();
			genericToken.parse(tree, function);
			
			String lastInstruction = function.getLastInstruction();
			if (lastInstruction.contains("call") && !lastInstruction.contains("call void"))
					removeLastInstruction(tree, function);
		}
		else if (token.equals("IF")) {
			genericToken = new IfToken();
			genericToken.parse(tree, function);
		}
		else if (token.equals("RETURN")) {
			genericToken = new ReturnToken();
			genericToken.parse(tree, function);
		}
		else {
			genericToken = new ExpToken();
			genericToken.parse(tree, function);
			removeLastInstruction(tree, function);
		}
		
		
		this.setCtsType(genericToken.getCtsType());
	}
	
	private void removeLastInstruction(Tree tree, Function function) {
 		Tree parent = tree.getParent();
		int parentType = parent.getType();
		String parentToken = Tokens.getToken(parentType);
		
		if (parentType == 0 // Main function 
		 || parentToken.equals("DEF")) {
			function.addInstruction("pop");
		}
	}
}
